//------------------------------------------------------------------------------
//	file midi_ports.c
//	brief
//		Display all midi port information
//
//	$Id: midi_sysex.c 278 2014-04-18 17:43:00Z ac.verbeck@gmail.com $
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
//	Copyright and Disclaimer Notice
//
//	Copyright (c) 2014 A.C. Verbeck
//
//	This file is part of winMIDI: windows MIDI -- a direct MIDI interface
//
//	winMIDI is free software: you can redistribute it and/or modify
//	it under the terms of the GNU General Public License as published by
//	the Free Software Foundation, either version 3 of the License, or
//	(at your option) any later version.
//
//	winMIDI is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//	GNU General Public License for more details.
//
//	You should have received a copy of the GNU General Public License
//	along with winMIDI. If not, see <http://www.gnu.org/licenses/>.
//
//------------------------------------------------------------------------------
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

#include <stdint.h>																//	Standard int types
#include <stdbool.h>															//	Bool

#include <popt.h>
#include <Windows.h>
#include <mmsystem.h>

#include "bi.h"
#include "debug.h"
#include "p_mem.h"

//----------------------------------------------------------------------------
// Local defines (options)
//----------------------------------------------------------------------------
#define OPT_PORT			0x0001
#define OPT_ABOUT			0x0100
#define OPT_VERBOSE			0x0200

//----------------------------------------------------------------------------
// Local defines (sysex buffers)
//----------------------------------------------------------------------------
#define SYSEX_BUFF_CT		1
#define SYSEX_BUFF_SZ		1024

//----------------------------------------------------------------------------
// Local data
//----------------------------------------------------------------------------
static poptContext		optCon;

//----------------------------------------------------------------------------
// Local functions
//----------------------------------------------------------------------------
static void CALLBACK MidiInProc(HMIDIIN hMidiIn, UINT wMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2);
static void Decode_MidiMsg(DWORD msg);
static void Decode_SysEx(MIDIHDR* msg);
static void about(void);

//------------------------------------------------------------------------------
//	Main application
//	- read parameters
//	- start the midi port
//	- wait for characters
//------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
	HMIDIIN		hMidiDevice = NULL;
	MIDIHDR		SysExHdr[SYSEX_BUFF_CT];

	DWORD		nMidiPort = 0;
	MMRESULT	rVal;

	uint32_t	opt=0;
	int			idx=0;
	int			in_char=0;
	bool		tr_run = true;

	struct poptOption optionsTable[] = {
		{ "port",	'p', POPT_ARG_INT,	  &nMidiPort,	 'p', "MIDI port to use",					NULL	},
		{ "about",	'a', POPT_ARG_NONE,	  NULL,			 'a', "display information about the app",	NULL	},
		{ "verbose",'v', POPT_ARG_NONE,	  NULL,			 'v', "enable verbose mode",				NULL	},
		POPT_AUTOHELP
		POPT_TABLEEND
	};

//------------------------------------------------------------------------------
//	Process arguments
//------------------------------------------------------------------------------
	optCon = poptGetContext(NULL, argc, (const char **)argv, optionsTable, 0);
	poptSetOtherOptionHelp(optCon, "[OPTIONS]*");
	if (argc == 1) {
		about();
	}
	while ((idx = poptGetNextOpt(optCon)) >= 0) {
		switch (idx) {
		case 'p':
			opt |= OPT_PORT;
			break;
		case 'a':
			opt |= OPT_ABOUT;
			break;
		case 'v':
			opt |= OPT_VERBOSE;
			break;
		}
	}
	if (idx < -1) {
		fprintf(stderr, "%s: %s\n",
		        poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
		        poptStrerror(idx));
		exit(opt);
	}
	if (opt & OPT_ABOUT) {
		bldinfoPrintBldInfo();
		exit(0);
	}
	TRACE_init((opt & OPT_VERBOSE) ? true : false);

//------------------------------------------------------------------------------
//	Check for MIDI ports
//------------------------------------------------------------------------------
	if (midiInGetNumDevs() == 0) {
		TRACE(INFO,"No Input MIDI devices\n")
		exit(1);
	}

//------------------------------------------------------------------------------
//	Open MIDI port
//------------------------------------------------------------------------------
	rVal = midiInOpen(&hMidiDevice, nMidiPort, (DWORD)(void*)MidiInProc, 0, CALLBACK_FUNCTION);
	if (rVal != MMSYSERR_NOERROR) {
		TRACE(INFO,"midiInOpen() failed. Error code:%d", rVal);
		exit(1);
	}

//------------------------------------------------------------------------------
//	Prepare buffers for incoming data
//------------------------------------------------------------------------------
	for (int i=0; i<SYSEX_BUFF_CT; i++) {
		SysExHdr[i].lpData = calloc(SYSEX_BUFF_SZ,1);
		SysExHdr[i].dwBufferLength = SYSEX_BUFF_SZ;
		SysExHdr[i].dwBytesRecorded = 0;
		SysExHdr[i].dwUser = i;
		SysExHdr[i].dwFlags = 0;
		midiInPrepareHeader(hMidiDevice, &SysExHdr[i], sizeof(SysExHdr));
		midiInAddBuffer(hMidiDevice, &SysExHdr[i], sizeof(SysExHdr));
	}

//------------------------------------------------------------------------------
//	Wait for q or ESC key
//------------------------------------------------------------------------------
	midiInStart(hMidiDevice);
	while (tr_run == true) {
		in_char = _getch();
		switch (in_char) {
		case 'q':
			tr_run = false;
			break;
		case VK_ESCAPE:
			tr_run = false;
			break;
		}
	}

//------------------------------------------------------------------------------
//	Un-prepare buffers
//	Stop and close the port
//------------------------------------------------------------------------------
	for (int i=0; i<SYSEX_BUFF_CT; i++) {
		midiInUnprepareHeader(hMidiDevice, &SysExHdr[i], sizeof(SysExHdr));
		free(SysExHdr[i].lpData);
	}
	midiInStop(hMidiDevice);
	midiInClose(hMidiDevice);

	return 0;
}

//----------------------------------------------------------------------------
// MIDI input driver callback
//----------------------------------------------------------------------------
static void CALLBACK MidiInProc(HMIDIIN hMidiIn, UINT wMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2)
{
	switch(wMsg) {
	case MIM_OPEN:
		TRACE(INFO, "MIM_OPEN");
		break;
	case MIM_CLOSE:
		TRACE(INFO, "MIM_CLOSE");
		break;
	case MIM_DATA:
		TRACE(INFO, "MIM_DATA: MIDI msg:%08x timestamp:%d", dwParam1, dwParam2);
		Decode_MidiMsg(dwParam1);
		break;
	case MIM_LONGDATA:
		TRACE(INFO, "MIM_LONGDATA: MIDI hdr:%08x timestamp:%d", dwParam1, dwParam2);
		Decode_SysEx((MIDIHDR*)dwParam1);
		break;
	case MIM_ERROR:
		TRACE(INFO, "MIM_ERROR");
		break;
	case MIM_LONGERROR:
		TRACE(INFO, "MIM_LONGERROR");
		break;
	case MIM_MOREDATA:
		TRACE(INFO, "MIM_MOREDATA");
		break;
	default:
		TRACE(INFO, "unknown wMsg");
		break;
	}
	return;
}

//----------------------------------------------------------------------------
// Decode MIDI message
//----------------------------------------------------------------------------
static void Decode_MidiMsg(DWORD msg)
{
	uint8_t midi_status = msg&0xff;
	uint8_t midi_b1 = (msg>>0x08)&0xff;
	uint8_t midi_b2 = (msg>>0x10)&0xff;

	printf("MIDI status:%02x ", midi_status);
	printf("byte 1:%02x ", midi_b1);
	printf("byte 2:%02x\n", midi_b2);
}

//----------------------------------------------------------------------------
// Decode SysEx message
//----------------------------------------------------------------------------
static void Decode_SysEx(MIDIHDR* msg)
{
	printf("SysEx decode:\n");
	printf("Buffer ID: %d\n",msg->dwUser);
	printf("Buffer Length/Recorded: %d/%d\n",msg->dwBufferLength, msg->dwBytesRecorded);
	p_mem((uint8_t*)msg->lpData, msg->dwBytesRecorded);
	printf("\n");
}


//------------------------------------------------------------------------------
//	brief
//		Display about
//
//	param
//		none
//
//	return
//		none
//------------------------------------------------------------------------------
static void about(void)
{
	bldinfoPrintBldInfo();
	poptPrintUsage(optCon, stderr, 0);
	exit(1);
}

//
//	End: midi_ports.c
//
